package org.devocean.groupbuying.web.interceptors;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tools.ant.types.CommandlineJava.SysProperties;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;

public class LocaleChangeInterceptor extends HandlerInterceptorAdapter {

	private String defaultLocale;

	/**
	 * Pre Intercept the request for uri language adaptation purpose
	 * <p>
	 * Actions :
	 * <p>
	 * - Replace language path variable ( Case : ContextPath/{lang}/***)
	 * <p>
	 * - Remove language path variable ( Case : ContextPath/{defaultLocale}/)
	 * <p>
	 * - Add Language path variable ( Case : ContextPath/**** | Home not
	 * included )
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler)
			throws ServletException {

		// System.out.println("prehandle frontend");

		@SuppressWarnings("unchecked")
		Map<String, String> pathVariables = ((Map<String, String>) request
				.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE));

		String newLocale = request.getParameter("lang"); // where
															// request?lang=XX
		String pvLang = pathVariables.get("lang");// where request/XX/
		String uri;
		String olduri = request.getRequestURI();

		boolean noCookie = true;

		if (request.getCookies() != null) {
			for (Cookie c : request.getCookies()) {
				if (c.getName().equalsIgnoreCase("clientLanguage")) {
					noCookie = false;

				}
			}

		}
		if (noCookie) {
			try {
				response.addCookie(new Cookie("clientLanguage",
						this.defaultLocale));
				response.sendRedirect(request.getContextPath() + "/cookie");
				return false;
			} catch (Exception e1) {
				e1.printStackTrace();
			}

		}

		if (olduri.endsWith(this.defaultLocale + "/")) {

			try {
				response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
				response.setHeader("Location", request.getContextPath());
				return false;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

		if (pvLang == null) {
			pvLang = this.defaultLocale;
		}

		if (newLocale != null && !pvLang.equals(newLocale)) {
			uri = olduri.replaceFirst("/[a-z]{2}/", "/" + newLocale + "/");

			if (olduri.endsWith(request.getContextPath() + "/")) {
				uri = olduri + newLocale + "/";
			}

			try {
				response.sendRedirect(uri);
				return false;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

		if (newLocale == null) {
			newLocale = pvLang;
		}

		LocaleResolver localeResolver = RequestContextUtils
				.getLocaleResolver(request);
		if (localeResolver == null) {
			throw new IllegalStateException(
					"No LocaleResolver found: not in a DispatcherServlet request?");
		}
		LocaleEditor localeEditor = new LocaleEditor();
		localeEditor.setAsText(newLocale);
		localeResolver.setLocale(request, response,
				(Locale) localeEditor.getValue());

		return true;
	}

	/**
	 * Post Intercept the request for uri generation
	 * <p>
	 * Actions :
	 * <p>
	 * - Generate localPath with newLocale handle
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		String newLocale = this.defaultLocale;
		if (request.getCookies() != null) {
			for (Cookie c : request.getCookies()) {
				if (c.getName().equalsIgnoreCase("clientLanguage")) {
					newLocale = c.getValue();
				}
			}

		}
		request.setAttribute("localPath", request.getContextPath() + "/"
				+ newLocale + "/");
		request.setAttribute("defaultLocalPath", request.getContextPath() + "/");

		super.postHandle(request, response, handler, modelAndView);
	}

	public String getDefaultLocale() {
		return defaultLocale;
	}

	public void setDefaultLocale(String defaultLocale) {
		this.defaultLocale = defaultLocale;
	}

}
